<?php
// ################################################################################################################
// ## Thumbnail Control Engine Files ##############################################################################
// ################################################################################################################
require_once('thumb_engine.php');

if(isset($__ts)) unset($__ts);
$__ts = array();

global $blog, $service, $__ts;

# Locale language file support, defualt is en-us.php
if (!isset($blog['blogLanguage'])) {
	$blog['blogLanguage'] = $service['language'];
}
// Locale language file support.
switch($blog['blogLanguage']) {
	case "zh-TW":
	case "zh-CN":
		$languageFile = 'lang/'.$blog['blogLanguage'].'.php';
	break;
	default:
		$languageFile = "";
}
if(!empty($languageFile)) include_once ($languageFile);
// ################################################################################################################
// ## Thumbnail Recent Process for List ###########################################################################
// ################################################################################################################
function categoryCheck($realCT,$tempCT){
	global $database, $blogid;
	$ct_cnt = count($tempCT);
	for($i=0;$i<$ct_cnt;$i++){
		$pid = POD::queryAll("SELECT id FROM {$database['prefix']}Categories WHERE blogid = {$blogid} AND parent = {$tempCT[$i]}");
		if($pid == NULL){
			if($realCT==$tempCT[$i]) return true;
		}else {
			foreach($pid as $item){
				if($realCT==$tempCT[$i] || $realCT == $item['id']) return true;
			}
		}
	}
}

function showThumbListView($target, $mother) {
	global $database, $blogid, $configVal, $hostURL, $blogURL, $folderURL, $service, $skinSetting, $pluginURL, $list, $view, $category, $paging, $skin, $blog, $suri, $commentList;
	requireComponent('Textcube.Model.Paging');
	requireComponent('Textcube.Function.misc');
	requireComponent('Needlworks.Cache.PageCache');
	require_once('lang/pluginLocal.php');

	$data = misc::fetchConfigVal($configVal);
	$data['lockimg'] = isset($data['lockimg']) ? $data['lockimg'] : 2;

	if(isset($list) && $data['uList'] && !$data['uNull']){
		$categories = getCategories($blogid);
		$ctArray = array(); $setCategory = array();
		foreach($categories as $category1){
			foreach($category1['children'] as $category2) array_push($ctArray, $category2['id']);
			array_push($ctArray, $category1['children']);
		}
		for($i=1; $i<=count($ctArray); $i++){
			$data['c'.$i] = isset($data['c'.$i]) ? $data['c'.$i] : "";
			if($data['c'.$i])
			array_push($setCategory, $data['c'.$i]);
		}
		if($data['call']){
				$setCategory = array();
				$categories = getCategories($blogid);
				$tree = getCategoryArray($categories);
				foreach($tree['children'] as $child){
					array_push($setCategory, $child['id']);
					foreach($child['children'] as $leaf){
						array_push($setCategory, $leaf['id']);
					}
				}
		}

		if((categoryCheck($category, $setCategory)==true)
			|| (($data['call'])?$suri['directive']=="/category":"" )
			|| (($data['p1'])?$suri['directive']=="/archive":"" )
			|| (($data['p2'])?$suri['directive']=="/search":"" )
			|| (($data['p3'])?$suri['directive']=="/tag":"" )
			|| (($data['p4'])?$suri['directive']=="/author":"" )
			){

			if(!isset($_GET['page']) && empty($_GET['page'])){
				$pagenum = 1;
			}else{
				$pagenum = $_GET['page'];
			}

			$data['totalview'] = $data['maxX']*$data['maxY'];
			$start = $data['totalview']*($pagenum-1);
			$limit = " limit {$start}, {$data['totalview']} ";
			if($category > 0){
				$subCT = POD::queryColumn("SELECT id FROM {$database['prefix']}Categories WHERE blogid = $blogid AND parent = $category");
				array_push($subCT, $category);
				$realCT = implode(',',$subCT);
				$checkSuri = " AND e.category in ({$realCT}) ";
			}

			if($data['call'] && $category==0){
				$ctArray = array();
				$categories = getCategories($blogid);
				$tree = getCategoryArray($categories);
				foreach($tree['children'] as $child){
					array_push($ctArray, $child['id']);
					foreach($child['children'] as $leaf){
						array_push($ctArray, $leaf['id']);
					}
				}
				array_push($ctArray, $category);
				$realCT = implode(',',$ctArray);
				$checkSuri = " AND e.category in ({$realCT}) ";
			}

			if($data['p1'] && $suri['directive'] == '/archive' && $suri['value'] == ''){
				$tyear		= date("Y");
				$tmonth		= date("m");
				$lastDay	= date('t',mktime(0,0,0,$tmonth,1,$tyear));
				$dateStart	= strtotime("{$tyear}-{$tmonth}-01 00:00:00");
				$dateEnd	= strtotime("{$tyear}-{$tmonth}-{$lastDay} 23:59:59");
				$checkSuri	= " AND (e.published >= ".$dateStart." AND e.published <= ".$dateEnd.") ";
			}else if($data['p1'] && $suri['directive'] == '/archive' && $suri['value'] != ''){
				$xyear	= substr($suri['value'], 0, 4);
				$xmonth = substr($suri['value'], 4, 2);
				$xday	= substr($suri['value'], 6, 2);
				if(!$xmonth){
					$dateStart	= strtotime("{$xyear}-01-01 00:00:00");
					$dateEnd	= strtotime("{$xyear}-12-31 23:59:59");
				}else{
					$lastDay	= date('t',mktime(0,0,0,$xmonth,1,$xyear));
					$dateStart	= strtotime("{$xyear}-{$xmonth}-01 00:00:00");
					$dateEnd	= strtotime("{$xyear}-{$xmonth}-{$lastDay} 23:59:59");
					if($xday){
						$dateStart	= strtotime("{$xyear}-{$xmonth}-{$xday} 00:00:00");
						$dateEnd	= strtotime("{$xyear}-{$xmonth}-{$xday} 23:59:59");
					}
				}
				$checkSuri = " AND (e.published >= ".$dateStart." AND e.published <= ".$dateEnd.") ";
			}

			if($data['p2'] && ($suri['directive'] == '/search') && $suri['value'] == ''){
				$checkSuri = "";
			}else if($data['p2'] && ($suri['directive'] == '/search') && $suri['value'] != ''){
				$search = POD::escapeString($suri['value']);
				$checkSuri = " AND (e.title LIKE '%$search%' OR e.content LIKE '%$search%') ";
			}

			if($data['fList'] && !$data['f5']) {
				$fileExtensionCheck = array();
				$data['f1'] ? array_push($fileExtensionCheck, " name like '%.jpg' ") : "";
				$data['f2'] ? array_push($fileExtensionCheck, " name like '%.jpeg' ") : "";
				$data['f3'] ? array_push($fileExtensionCheck, " name like '%.gif' ") : "";
				$data['f4'] ? array_push($fileExtensionCheck, " name like '%.png' ") : "";
				$fileExtensionCheck = implode(" OR ", $fileExtensionCheck);
			}
			$attachCheckA = ($data['fList'] && !$data['f5'])?" , (SELECT parent FROM {$database['prefix']}Attachments WHERE blogid = {$blogid} AND (". $fileExtensionCheck .") GROUP BY parent ) a ":"";
			$attachCheckB = ($data['fList'] && !$data['f5'])?" AND e.id = a.parent ":"";

			$visibility = doesHaveOwnership()?'':' AND e.visibility > 0 ' . getPrivateCategoryExclusionQuery($blogid);

			if($data['p3'] && ($suri['directive'] == '/tag') && $suri['value'] != ''){
				$checkSuri = "";
				$tag = $suri['value'];
				$data['listcount'] = POD::queryCell("SELECT count(*) FROM {$database['prefix']}Tags t, {$database['prefix']}TagRelations r, {$database['prefix']}Entries e {$attachCheckA} WHERE r.entry = e.id {$visibility} AND e.category > 0 AND t.id = r.tag AND r.blogid = {$blogid} AND e.blogid = {$blogid} AND t.name = '" . POD::escapeString($tag) . "' {$attachCheckB}");
				$result1 = POD::query("SELECT e.id, e.title, e.slogan, e.published, e.comments, e.visibility, e.content FROM {$database['prefix']}Tags t, {$database['prefix']}TagRelations r, {$database['prefix']}Entries e {$attachCheckA} WHERE r.entry = e.id {$visibility} AND e.category > 0 AND t.id = r.tag AND r.blogid = {$blogid} AND e.blogid = {$blogid} AND t.name = '" . POD::escapeString($tag) . "' {$attachCheckB} ORDER BY published DESC {$limit}");
				$paging_sql = "SELECT e.id, e.title, e.slogan, e.published, e.comments FROM {$database['prefix']}Tags t, {$database['prefix']}TagRelations r, {$database['prefix']}Entries e {$attachCheckA} WHERE r.entry = e.id {$visibility} AND e.category > 0 AND t.id = r.tag AND r.blogid = {$blogid} AND e.blogid = {$blogid} AND t.name = '" . POD::escapeString($tag) . "' {$attachCheckB}";
			}else if($suri['directive'] == '/author' && $suri['value'] != ''){
				$checkSuri = "";
				$authorId = User::getUserIdByName($suri['value']);
				$data['listcount']  = POD::queryCell("SELECT count(*) FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.userid in ({$authorId}) AND e.category >= 0 {$visibility} {$checkSuri} {$attachCheckB}");
				$result1 = POD::query("SELECT e.id, e.title, e.slogan, e.published, e.comments, e.visibility, e.content FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.userid = {$authorId} AND e.category >= 0 {$visibility} {$checkSuri} {$attachCheckB} ORDER BY e.published DESC {$limit}");
				$paging_sql = "SELECT * FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.userid = {$authorId} AND e.category >= 0 {$visibility} {$checkSuri} {$attachCheckB} ORDER BY e.published DESC";
			}else{
				$data['listcount'] = POD::queryCell("SELECT count(*) FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.category >= 0 {$visibility} {$checkSuri} {$attachCheckB}");
				$result1 = POD::query("SELECT e.id, e.title, e.slogan, e.published, e.comments, e.visibility, e.content FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.category >= 0 {$visibility} {$checkSuri} {$attachCheckB} ORDER BY e.published DESC {$limit}");
				$paging_sql = "SELECT * FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.category >= 0 {$visibility} {$checkSuri} {$attachCheckB} ORDER BY e.published DESC";
			}

			list($temp, $temp_paging) = Paging::fetchWithPaging($paging_sql, $pagenum, $data['totalview'], "$folderURL/{$suri['value']}",'?page=');

			if(!isset($data['header'])){
				$thumb_list  = "<div class=\"searchList\"><h3>'<span class=\"keycolor\">[##_list_conform_##]</span>".pluginLang::plts('에 해당되는 글 [##_list_count_##]건')."</h3>";
			}else{
				$thumb_list  = $data['header'];
			}
			$thumb_list .= "\t\t<div id=\"thumb_main\"><table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>\n";
			$thumb_cnt = 0;
			while(list($eid, $title, $slogan, $date, $comment_cnt, $visibility, $content) = POD::fetch($result1, 'array')) {
				$tempVisibility = $visibility;
				$visibility = $data['lockimg'] == 1 ? 2 : $visibility;
				$filename = getAttachmentExtract_Thumb($content);
				if($filename || $data['urlimg']==1) {
					if (strpos($filename, 'http://') !== 0) {
						if (strpos($filename, '/') !== false) {
							$targetfile = ROOT."/cache/thumbnail/{$blogid}/JP_Thumb/list/thumb_".basename($filename);
							$sourcefile = ROOT.str_replace(array("./","../"), array("",""), $filename);
						} else {
							$targetfile = ROOT."/cache/thumbnail/{$blogid}/JP_Thumb/list/thumb_{$filename}";
							$sourcefile = ROOT."/attach/{$blogid}/{$filename}";
						}
						$link_filepath = NULL;
					}else{
						$link_filepath = $filename;
						$filename = NULL;
						$targetfile = NULL;
						$sourcefile = NULL;
					}
					$img_tag = get_thumbTag($eid, $filename, $link_filepath, &$sourcefile, $data['width'], $data['height'], $targetfile, $mode="list", $data['resize'], $data['quality'], $data['urlimg']);
					if(basename($img_tag[2]) != "no_screenshot.gif"){
						$img_tag[2] = $service['path']."/thumbnail/{$blogid}/JP_Thumb/list/".basename($img_tag[2]);
					}
					if(!getAttachCheck_Thumb(misc::getFileExtension($img_tag[2])) || ($visibility == 1 && !doesHaveOwnership())) $img_tag = array($data['width'], $data['height'], "{$pluginURL}/images/protect.gif");
				}else{
					$img_tag = array($data['width'], $data['height'], "{$pluginURL}/images/no_screenshot.gif");
				}

				$lightbox_src = !is_null($link_filepath) ? $link_filepath : "{$service['path']}/attach/$blogid/{$filename}";
				$permalink = "$blogURL/" . ($blog['useSloganOnPost'] ? "entry/" . URL::encode($slogan,$service['useEncodedURL']) : $eid);

				if($data['comment'] == 1){
					(($comment_cnt == 0)? $entry_comment="":$entry_comment=" <span class=\"thumb_cnt\">({$comment_cnt})</span>");
				}

				if($data['title'] == 1){
					$entry_title = "<div class=\"thumb_title\"><a href=\"{$permalink}\">".htmlspecialchars(UTF8::lessenAsEm($title, $data['title_length']))."</a>{$entry_comment}</div>";
				}

				if($data['date'] == 1){
					$entry_date = "<div class=\"thumb_date\">".Timestamp::format3($date)."</div>";
				}

				if(($thumb_cnt % $data['maxX']) == ($data['maxX']-1)){
					$line_chk = ($thumb_cnt == ($data['totalview']-1))?"\t\t</tr>\n":"\t\t</tr>\n\t\t<tr>\n";
				}else{$line_chk = "";}

				if($tempVisibility == 1 && !doesHaveOwnership()) $title = pluginLang::plts('보호되어 있는 글입니다.');

				if($data['lightbox'] == 1 && $tempVisibility != 1 && (getAttachCheck_Thumb(misc::getFileExtension($sourcefile)) || $link_filepath)){
					$thumb_list .= "\t\t<td valign=\"{$data['valign']}\" align=\"{$data['align']}\"><div class=\"thumb_item\"><div class=\"thumb_image\"><a href=\"{$lightbox_src}\" rel=\"lightbox\" title=\"{$title}\"><img src=\"{$img_tag[2]}\" width=\"$img_tag[0]\" height=\"$img_tag[1]\" border=\"0\" alt=\"{$title}\" class=\"thumb_border\" /></a></div>{$entry_title}{$entry_date}</div></td>\n{$line_chk}";
				}else{
					$thumb_list .= "\t\t<td valign=\"{$data['valign']}\" align=\"{$data['align']}\"><div class=\"thumb_item\"><div class=\"thumb_image\"><a href=\"{$permalink}\" title=\"{$title}\"><img src=\"{$img_tag[2]}\" width=\"$img_tag[0]\" height=\"$img_tag[1]\" border=\"0\" alt=\"{$title}\" class=\"thumb_border\" /></a></div>{$entry_title}{$entry_date}</div></td>\n{$line_chk}";
				}
				$thumb_cnt++;
			}

			if ($thumb_cnt<($data['totalview']-1)) {
				for($i=($thumb_cnt % $data['maxX']==0)? $data['maxX']+1:($thumb_cnt % $data['maxX']);$i < $data['maxX'];$i++){
					$thumb_list .= "\t\t<td>&nbsp;</td>\n";
				}
				$thumb_list .= "\t\t</tr>\n";
			}

			$thumb_list .= "\t\t</table></div><div class=\"divide\"></div>\n";

			if(!isset($data['footer'])){
				$thumb_list .= "</div>";
			}else{
				$thumb_list .= $data['footer'];
			}

			misc::dress('list_conform', htmlspecialchars($list['title']), $thumb_list);
			misc::dress('list_count', $thumb_cnt."/".$data['listcount'], $thumb_list);
			misc::dress('rplist', "", $thumb_list);
			misc::dress('tblist', "", $thumb_list);

			if(isset($paging)) {
				$paging = $temp_paging;
				misc::dress('paging_list',Paging::getPagingView($temp_paging,$skin->paging,$skin->pagingItem),$view);
			}

			$directive = str_replace("/", "", $suri['directive']);
			if($service['pagecache'] == true){
				$cache = new pageCache;
				if($directive == "category"){
					$cache->name = "List_ThumbPaging_".$directive."_".$category."_".$suri['page'];
				}else{
					$cache->name = "List_ThumbPaging_".$directive."_".$suri['page'];
				}
				$cache->contents = Paging::getPagingView($temp_paging,$skin->paging,$skin->pagingItem);
				$cache->dbContents = Paging::getPagingView($temp_paging,$skin->paging,$skin->pagingItem);
				$cache->update();
				unset($cache);
			}
			$target = $thumb_list;
		}
	}
	return $target;
}

function showThumbDressProcess($target){
	global $skin, $blogid, $category, $skinSetting, $suri, $blog, $service, $configVal;
	requireComponent('Textcube.Function.misc');
	requireComponent('Needlworks.Cache.PageCache');
	$data = misc::fetchConfigVal($configVal);
	if($data['uList'] && !$data['uNull']){
		$directive = str_replace("/", "", $suri['directive']);
		$categories = getCategories($blogid);
		$ctArray = array(); $setCategory = array();
		foreach($categories as $category1){
			foreach($category1['children'] as $category2) array_push($ctArray, $category2['id']);
			array_push($ctArray, $category1['children']);
		}
		for($i=1; $i<=count($ctArray); $i++){
			$data['c'.$i] = isset($data['c'.$i]) ? $data['c'.$i] : "";
			if($data['c'.$i])
			array_push($setCategory, $data['c'.$i]);
		}
		if($data['call']){
				$setCategory = array();
				$categories = getCategories($blogid);
				$tree = getCategoryArray($categories);
				foreach($tree['children'] as $child){
					array_push($setCategory, $child['id']);
					foreach($child['children'] as $leaf){
						array_push($setCategory, $leaf['id']);
					}
				}
		}
		if((categoryCheck($category, $setCategory)==true)
			|| (($data['call'])?$suri['directive']=="/category":"" )
			|| (($data['p1'])?$suri['directive']=="/archive":"" )
			|| (($data['p2'])?$suri['directive']=="/search":"" )
			|| (($data['p3'])?$suri['directive']=="/tag":"" )
			|| (($data['p3'])?$suri['directive']=="/author":"" )
		){
			if($directive == "category"){
				$data['showListOnCategory'] = (isset($data['showListOnCategory']) && !empty($data['showListOnCategory'])) ? $data['showListOnCategory'] : 2;
				$skinSetting['showListOnCategory'] = $data['showListOnCategory'];
				if($skinSetting['showListOnCategory'] == 1 || $skinSetting['showListOnCategory'] == 3){
					$blog['entriesOnList'] = $data['maxX']*$data['maxY'];
				}
			}else if($directive == "archive"){
				$data['showListOnCategory'] = (isset($data['showListOnCategory']) && !empty($data['showListOnCategory'])) ? $data['showListOnCategory'] : 2;
				$skinSetting['showListOnArchive'] = $data['showListOnCategory'];
				if($skinSetting['showListOnArchive'] == 1 || $skinSetting['showListOnArchive'] == 3){
					$blog['entriesOnList'] = $data['maxX']*$data['maxY'];
				}
			}else if($directive == "search"){
				$data['showListOnCategory'] = (isset($data['showListOnCategory']) && !empty($data['showListOnCategory'])) ? $data['showListOnCategory'] : 2;
				$skinSetting['showListOnSearch'] = $data['showListOnCategory'];
				if($skinSetting['showListOnSearch'] == 1 || $skinSetting['showListOnSearch'] == 3){
					$blog['entriesOnList'] = $data['maxX']*$data['maxY'];
				}
			}else if($directive == "tag"){
				$data['showListOnCategory'] = (isset($data['showListOnCategory']) && !empty($data['showListOnCategory'])) ? $data['showListOnCategory'] : 2;
				$skinSetting['showListOnTag'] = $data['showListOnCategory'];
				if($skinSetting['showListOnTag'] == 1 || $skinSetting['showListOnTag'] == 3){
					$blog['entriesOnList'] = $data['maxX']*$data['maxY'];
				}
			}else if($directive == "author"){
				$data['showListOnCategory'] = (isset($data['showListOnCategory']) && !empty($data['showListOnCategory'])) ? $data['showListOnCategory'] : 2;
				$skinSetting['showListOnAuthor'] = $data['showListOnCategory'];
				if($skinSetting['showListOnAuthor'] == 1 || $skinSetting['showListOnAuthor'] == 3){
					$blog['entriesOnList'] = $data['maxX']*$data['maxY'];
				}
			}

			$skin = new Skin($skinSetting['skin']);
			$cache = new pageCache;

			misc::dress('rplist', "", $skin->skin);
			misc::dress('tblist', "", $skin->skin);
			misc::dress('article_rep', "", $skin->skin);

			if($service['pagecache'] == true){
				if($directive == "category"){
					$cache->name = "List_ThumbPaging_".$directive."_".$category."_".$suri['page'];
				}else{
					$cache->name = "List_ThumbPaging_".$directive."_".$suri['page'];
				}

				if($cache->load()){
					 misc::dress('paging', $cache->contents, $skin->skin);
				}else{
					$cache->reset();
					if($directive == "category"){
						$cache->name = "List_ThumbPaging_".$directive."_".$category."_".$suri['page'];
					}else{
						$cache->name = "List_ThumbPaging_".$directive."_".$suri['page'];
					}
					$cache->purge();
				}
				unset($cache);
			}
		}
	}
	return $target;
}


// ################################################################################################################
// ## Thumbnail Recent View Process for Sidebar ###################################################################
// ################################################################################################################
function categoryCheck_Sidebar($tempCT){
	global $database, $blogid;
	$setCategory = array();
	foreach($tempCT as $item){
		array_push($setCategory, $item);
		$pid = POD::queryAll("SELECT id FROM {$database['prefix']}Categories WHERE blogid = {$blogid} AND parent = {$item} ORDER BY id asc");
		if($pid){
			foreach($pid as $items){
				array_push($setCategory, $items['id']);
			}
		}
	}
	$setCategory = array_unique($setCategory);
	return $setCategory;
}

function showSidebarPhotoView($parameter) {
	global $database, $blogid, $configVal, $hostURL, $blogURL, $pluginURL, $service, $blog;
	require_once('lang/pluginLocal.php');
	if (isset($parameter['preview'])) {
		// preview mode
		$retval = pluginLang::plts('썸네일 이미지를 사이드바에 출력하여 보여 줍니다.');
		return $retval;
	}
	requireComponent('Textcube.Function.misc');
	$data = misc::fetchConfigVal($configVal);
	$data['lockimg'] = isset($data['lockimg']) ? $data['lockimg'] : 2;

	if($data['uSide'] && !$data['uNull']){
		$categories = getCategories($blogid);
		$ctArray = array(); $setCategory = array();
		foreach($categories as $category1){
			foreach($category1['children'] as $category2) array_push($ctArray, $category2['id']);
			array_push($ctArray, $category1['children']);
		}

		for($i=1; $i<=count($ctArray); $i++){
			$data['c'.$i] = isset($data['c'.$i]) ? $data['c'.$i] : "";
			if($data['c'.$i])
			array_push($setCategory, $data['c'.$i]);
		}

		if($data['call']){
				$setCategory = array();
				array_push($setCategory, 0);
				$categories = getCategories($blogid);
				$tree = getCategoryArray($categories);
				foreach($tree['children'] as $child){
					array_push($setCategory, $child['id']);
					foreach($child['children'] as $leaf){
						array_push($setCategory, $leaf['id']);
					}
				}
		}

		$data['category'] = implode(',', categoryCheck_Sidebar($setCategory));
		$data['category'] = ($data['category'])?" AND e.category in ({$data['category']}) ":"";

		switch($data['sb_loading']){
			case 1:$thumb_load = "e.published DESC";break;
			case 2:$thumb_load = "rand()";break;
			case 3:$thumb_load = "e.comments DESC";break;
			default:return false;
		}
		// Thumbnail control process ######################################################################################
		$data['totalview'] = $data['sb_maxX']*$data['sb_maxY'];
		$limit = " limit {$data['totalview']} ";

		if($data['fSide']){
			if(!$data['f5']) {
				$fileExtensionCheck = array();
				$data['f1'] ? array_push($fileExtensionCheck, " name like '%.jpg' ") : "";
				$data['f2'] ? array_push($fileExtensionCheck, " name like '%.jpeg' ") : "";
				$data['f3'] ? array_push($fileExtensionCheck, " name like '%.gif' ") : "";
				$data['f4'] ? array_push($fileExtensionCheck, " name like '%.png' ") : "";
				$fileExtensionCheck = implode(" OR ", $fileExtensionCheck);
			}
			$attachCheckA = (!$data['f5'])?" , (SELECT parent FROM {$database['prefix']}Attachments WHERE blogid = {$blogid} AND (". $fileExtensionCheck .") GROUP BY parent ) a ":"";
			$attachCheckB = (!$data['f5'])?" AND e.id = a.parent ":"";
		}
		$visibility = doesHaveOwnership()?'':' AND e.visibility > 0' . getPrivateCategoryExclusionQuery($blogid);
		$result1 = POD::query("SELECT e.id, e.title, e.slogan, e.published, e.comments, e.visibility, e.content FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.category >= 0 {$visibility} {$data['category']} {$attachCheckB} ORDER BY {$thumb_load} {$limit}");

		if(!isset($data['sb_header'])){
			$thumb_list  = "<div class=\"sidebar_photos\"><h3>sidebar photos</h3>";
		}else{
			$thumb_list  = $data['sb_header'];
		}

		$thumb_list .= "\t\t<div id=\"sidebarphotos_main\">\n\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>\n";
		$thumb_cnt = 0;
		while(list($eid, $title, $slogan, $date, $comment_cnt, $visibility, $content) = POD::fetch($result1, 'array')) {
			$tempVisibility = $visibility;
			$visibility = $data['lockimg'] == 1 ? 2 : $visibility;
			$filename = getAttachmentExtract_Thumb($content);
			if($filename || $data['urlimg']==1){
				if (strpos($filename, 'http://') !== 0){
					if (strpos($filename, '/') !== false) {
						$targetfile = ROOT."/cache/thumbnail/{$blogid}/JP_Thumb/sidebar/thumb_".basename($filename);
						$sourcefile = ROOT.str_replace(array("./","../"), array("",""), $filename);
					} else {
						$targetfile = ROOT."/cache/thumbnail/{$blogid}/JP_Thumb/sidebar/thumb_{$filename}";
						$sourcefile = ROOT."/attach/$blogid/{$filename}";
					}
					$link_filepath = NULL;
				}else{
					$link_filepath = $filename;
					$filename = NULL;
					$targetfile = NULL;
					$sourcefile = NULL;
				}
				$img_tag = get_thumbTag($eid, $filename, $link_filepath, &$sourcefile, $data['sb_width'], $data['sb_height'], $targetfile, $mode="side", $data['sb_resize'], $data['quality'], $data['urlimg']);
				if(basename($img_tag[2]) != "no_screenshot.gif"){
					$img_tag[2] = $service['path']."/thumbnail/{$blogid}/JP_Thumb/sidebar/".basename($img_tag[2]);
				}
				if(!getAttachCheck_Thumb(misc::getFileExtension($img_tag[2])) || ($visibility == 1 && !doesHaveOwnership())) $img_tag = array($data['sb_width'], $data['sb_height'], "{$pluginURL}/images/protect.gif");
			}else{
				$img_tag = array($data['sb_width'], $data['sb_height'], "{$pluginURL}/images/no_screenshot.gif");
			}


			$lightbox_src = !is_null($link_filepath) ? $link_filepath : "{$service['path']}/attach/$blogid/{$filename}";
			$permalink = "$blogURL/" . ($blog['useSloganOnPost'] ? "entry/" . URL::encode($slogan,$service['useEncodedURL']) : $eid);

			$entry_comment = ($comment_cnt != 0 && $data['sb_comment'] == 1)?" <span class=\"thumb_cnt\">({$comment_cnt})</span>":"";

			$entry_title = ($data['sb_title'] == 1)?"<div class=\"thumb_title\"><a href=\"{$permalink}\">".htmlspecialchars(UTF8::lessenAsEm($title, $data['sb_title_length']))."</a>{$entry_comment}</div>":"";

			$entry_date = ($data['sb_date'] == 1)?"<div class=\"thumb_date\">".Timestamp::format3($date)."</div>":"";

			if(($thumb_cnt % $data['sb_maxX']) == ($data['sb_maxX']-1)){
				$line_chk = ($thumb_cnt == ($data['totalview']-1))?"\t\t</tr>\n":"\t\t</tr>\n\t\t<tr>\n";
			}else{$line_chk = "";}

			if($tempVisibility == 1 && !doesHaveOwnership()) $title = pluginLang::plts('보호되어 있는 글입니다.');

			if($data['sb_lightbox'] == 1 && $tempVisibility != 1 && (getAttachCheck_Thumb(misc::getFileExtension($sourcefile)) || $link_filepath)){
				$thumb_list .= "\t\t<td valign=\"{$data['sb_valign']}\" align=\"{$data['sb_align']}\"><div class=\"thumb_item\"><div class=\"thumb_image\"><a href=\"{$lightbox_src}\" rel=\"lightbox\" title=\"{$title}\"><img src=\"{$img_tag[2]}\" width=\"$img_tag[0]\" height=\"$img_tag[1]\" border=\"0\" alt=\"{$title}\" class=\"thumb_border\" /></a></div>{$entry_title}{$entry_date}</div></td>\n{$line_chk}";
			}else{
				$thumb_list .= "\t\t<td valign=\"{$data['sb_valign']}\" align=\"{$data['sb_align']}\"><div class=\"thumb_item\"><div class=\"thumb_image\"><a href=\"{$permalink}\" title=\"{$title}\"><img src=\"{$img_tag[2]}\" width=\"$img_tag[0]\" height=\"$img_tag[1]\" border=\"0\" alt=\"{$title}\" class=\"thumb_border\" /></a></div>{$entry_title}{$entry_date}</div></td>\n{$line_chk}";
			}
			$thumb_cnt++;
		}
		if ($thumb_cnt<($data['totalview']-1)) {
			for($i=($thumb_cnt % $data['sb_maxX']==0)? $data['sb_maxX']+1:($thumb_cnt % $data['sb_maxX']);$i < $data['sb_maxX'];$i++){
				$thumb_list .= "\t\t<td>&nbsp;</td>\n";
			}
			$thumb_list .= "\t\t</tr>\n";
		}
		$target = $thumb_list."\t\t</table>\n\t\t</div>\n";

		if(!isset($data['sb_footer'])){
			$target .= "</div>";
		}else{
			$target .= $data['sb_footer'];
		}
	}
	return $target;
}

// ################################################################################################################
// ## Thumbnail Recent View Process for Cover #####################################################################
// ################################################################################################################
function categoryCheck_Cover($tempCT){
	global $database, $blogid;
	$setCategory = array();
	foreach($tempCT as $item){
		array_push($setCategory, $item);
		$pid = POD::queryAll("SELECT id FROM {$database['prefix']}Categories WHERE blogid = {$blogid} AND parent = {$item} ORDER BY id asc");
		if($pid){
			foreach($pid as $items){
				array_push($setCategory, $items['id']);
			}
		}
	}
	$setCategory = array_unique($setCategory);
	return $setCategory;
}

function showCoverPhotoView($parameters) {
	global $database, $blogid, $configVal, $hostURL, $blogURL, $pluginURL, $service, $blog;
	requireComponent('Textcube.Function.misc');
	require_once('lang/pluginLocal.php');
	$data = misc::fetchConfigVal($configVal);
	$data['lockimg'] = isset($data['lockimg']) ? $data['lockimg'] : 2;

	if (isset($parameters['preview'])) {
		// preview mode
		$retval = pluginLang::plts("썸네일 이미지를 커버페이지에 출력하여 보여 줍니다. (특정 카테고리를 선택하려면 '편집'에서 파란색의 <font color='blue'>'카테고리 선택'</font>을 클릭하여 원하는 카테고리를 선택할 수 있습니다.)");
//		return htmlspecialchars($retval);
		return $retval;
	}
	$getCategoryID = isset($parameters['categoryName']) ? $parameters['categoryName'] : '';
	$getThumbMaxY = isset($parameters['thumbMaxY']) ? $parameters['thumbMaxY'] : $data['cv_maxY'];

	if($data['uCover'] && !$data['uNull']){

		$cache = new PageCache;
		$cache->name = 'JP_ShowCoverPhoto_' . $getCategoryID;
		if($cache->load()) { //If successful loads
			if((Timestamp::getUNIXtime() - $cache->dbContents) < 300) {
				return $cache->contents;
			}
		}

		$categories = getCategories($blogid);
		$ctArray = array(); $setCategory = array();
		foreach($categories as $category1){
			foreach($category1['children'] as $category2) array_push($ctArray, $category2['id']);
			array_push($ctArray, $category1['children']);
		}
		for($i=1; $i<=count($ctArray); $i++){
			$data['c'.$i] = isset($data['c'.$i]) ? $data['c'.$i] : "";
			if($data['c'.$i])
			array_push($setCategory, $data['c'.$i]);
		}

		if($data['call']){
				$setCategory = array();
				array_push($setCategory, 0);
				$categories = getCategories($blogid);
				$tree = getCategoryArray($categories);
				foreach($tree['children'] as $child){
					array_push($setCategory, $child['id']);
					foreach($child['children'] as $leaf){
						array_push($setCategory, $leaf['id']);
					}
				}
		}

		if(!empty($getCategoryID)){
			$tempCategories = POD::queryColumn("SELECT id FROM {$database['prefix']}Categories WHERE blogid = $blogid AND parent = $getCategoryID");
			array_push($tempCategories, $getCategoryID);
		}

		$data['category'] = !empty($getCategoryID) ? implode(', ', $tempCategories) : implode(',', categoryCheck_Cover($setCategory));
		$data['category'] = ($data['category'])?" AND e.category in ({$data['category']}) ":"";
		switch($data['cv_loading']){
			case 1:$thumb_load = "e.published DESC";break;
			case 2:$thumb_load = "rand()";break;
			case 3:$thumb_load = "e.comments DESC";break;
			default:return false;
		}
		// Thumbnail control process ######################################################################################
		$data['cv_maxY'] = !empty($getThumbMaxY) ? $getThumbMaxY : $data['cv_maxY'];
		$data['totalview'] = $data['cv_maxX']*$data['cv_maxY'];
		$limit = " limit {$data['totalview']} ";

		if($data['fCover']){
			if(!$data['f5']) {
				$fileExtensionCheck = array();
				$data['f1'] ? array_push($fileExtensionCheck, " name like '%.jpg' ") : "";
				$data['f2'] ? array_push($fileExtensionCheck, " name like '%.jpeg' ") : "";
				$data['f3'] ? array_push($fileExtensionCheck, " name like '%.gif' ") : "";
				$data['f4'] ? array_push($fileExtensionCheck, " name like '%.png' ") : "";
				$fileExtensionCheck = implode(" OR ", $fileExtensionCheck);
			}
			$attachCheckA = (!$data['f5'])?" , (SELECT parent FROM {$database['prefix']}Attachments WHERE blogid = {$blogid} AND (". $fileExtensionCheck .") GROUP BY parent ) a ":"";
			$attachCheckB = (!$data['f5'])?" AND e.id = a.parent ":"";
		}
		$visibility = doesHaveOwnership()?'':' AND e.visibility > 0' . getPrivateCategoryExclusionQuery($blogid);
		$result1 = POD::query("SELECT e.id, e.title, e.slogan, e.published, e.comments, e.visibility, e.content FROM {$database['prefix']}Entries e {$attachCheckA} WHERE e.blogid = {$blogid} AND e.category >= 0 {$visibility} {$data['category']} {$attachCheckB} ORDER BY {$thumb_load} {$limit}");

		if(!isset($data['cv_header'])){
			$thumb_list  = "<div class=\"cover_photos\">";
		}else{
			$thumb_list  = $data['cv_header'];
		}

		$thumb_list .= !empty($getCategoryID) ? "<h3>".ucwords(getCategoryNameById($blogid, $getCategoryID))."</h3>" : "<h3>Cover photos</h3>";
		$thumb_list .= "\t\t<div class=\"coverphotos_main\">\n\t\t<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\"><tr>\n";
		$thumb_cnt = 0;
		while(list($eid, $title, $slogan, $date, $comment_cnt, $visibility, $content) = POD::fetch($result1, 'array')) {
			$tempVisibility = $visibility;
			$visibility = $data['lockimg'] == 1 ? 2 : $visibility;
			$filename = getAttachmentExtract_Thumb($content);
			if($filename || $data['urlimg']==1){
				if (strpos($filename, 'http://') !== 0){
					if (strpos($filename, '/') !== false) {
						$targetfile = ROOT."/cache/thumbnail/{$blogid}/JP_Thumb/coverphoto/thumb_".basename($filename);
						$sourcefile = ROOT.str_replace(array("./","../"), array("",""), $filename);
					} else {
						$targetfile = ROOT."/cache/thumbnail/{$blogid}/JP_Thumb/coverphoto/thumb_{$filename}";
						$sourcefile = ROOT."/attach/$blogid/{$filename}";
					}
					$link_filepath = NULL;
				}else{
					$link_filepath = $filename;
					$filename = NULL;
					$targetfile = NULL;
					$sourcefile = NULL;
				}
				$img_tag = get_thumbTag($eid, $filename, $link_filepath, &$sourcefile, $data['cv_width'], $data['cv_height'], $targetfile, $mode="cover", $data['cv_resize'], $data['quality'], $data['urlimg']);
				if(basename($img_tag[2]) != "no_screenshot.gif"){
					$img_tag[2] = $service['path']."/thumbnail/{$blogid}/JP_Thumb/coverphoto/".basename($img_tag[2]);
				}
				if(!getAttachCheck_Thumb(misc::getFileExtension($img_tag[2])) || ($visibility == 1 && !doesHaveOwnership())) $img_tag = array($data['cv_width'], $data['cv_height'], "{$pluginURL}/images/protect.gif");
			}else{
				$img_tag = array($data['cv_width'], $data['cv_height'], "{$pluginURL}/images/no_screenshot.gif");
			}

			$lightbox_src = !is_null($link_filepath) ? $link_filepath : "{$service['path']}/attach/$blogid/{$filename}";
			$permalink = "$blogURL/" . ($blog['useSloganOnPost'] ? "entry/" . URL::encode($slogan,$service['useEncodedURL']) : $eid);

			$entry_comment = ($comment_cnt != 0 && $data['cv_comment'] == 1)?" <span class=\"thumb_cnt\">({$comment_cnt})</span>":"";

			$entry_title = ($data['cv_title'] == 1)?"<div class=\"thumb_title\"><a href=\"{$permalink}\">".htmlspecialchars(UTF8::lessenAsEm($title, $data['cv_title_length']))."</a>{$entry_comment}</div>":"";

			$entry_date = ($data['cv_date'] == 1)?"<div class=\"thumb_date\">".Timestamp::format3($date)."</div>":"";

			if(($thumb_cnt % $data['cv_maxX']) == ($data['cv_maxX']-1)){
				$line_chk = ($thumb_cnt == ($data['totalview']-1))?"\t\t</tr>\n":"\t\t</tr>\n\t\t<tr>\n";
			}else{$line_chk = "";}

			if($tempVisibility == 1 && !doesHaveOwnership()) $title = pluginLang::plts('보호되어 있는 글입니다.');

			if($data['cv_lightbox'] == 1 && $tempVisibility != 1 && (getAttachCheck_Thumb(misc::getFileExtension($sourcefile)) || $link_filepath)){
				$thumb_list .= "\t\t<td valign=\"{$data['cv_valign']}\" align=\"{$data['cv_align']}\"><div class=\"thumb_item\"><div class=\"thumb_image\"><a href=\"{$lightbox_src}\" rel=\"lightbox\" title=\"{$title}\"><img src=\"{$img_tag[2]}\" width=\"$img_tag[0]\" height=\"$img_tag[1]\" border=\"0\" alt=\"{$title}\" class=\"thumb_border\" /></a></div>{$entry_title}{$entry_date}</div></td>\n{$line_chk}";
			}else{
				$thumb_list .= "\t\t<td valign=\"{$data['cv_valign']}\" align=\"{$data['cv_align']}\"><div class=\"thumb_item\"><div class=\"thumb_image\"><a href=\"{$permalink}\" title=\"{$title}\"><img src=\"{$img_tag[2]}\" width=\"$img_tag[0]\" height=\"$img_tag[1]\" border=\"0\" alt=\"{$title}\" class=\"thumb_border\" /></a></div>{$entry_title}{$entry_date}</div></td>\n{$line_chk}";
			}
			$thumb_cnt++;
		}
		if ($thumb_cnt<($data['totalview']-1)) {
			for($i=($thumb_cnt % $data['cv_maxX']==0)? $data['cv_maxX']+1:($thumb_cnt % $data['cv_maxX']);$i < $data['cv_maxX'];$i++){
				$thumb_list .= "\t\t<td>&nbsp;</td>\n";
			}
			$thumb_list .= "\t\t</tr>\n";
		}
		$target = $thumb_list."\t\t</table>\n\t\t</div>\n";

		if(!isset($data['cv_footer'])){
			$target .= "</div>";
		}else{
			$target .= $data['cv_footer'];
		}

		$cache->contents = $target;
		$cache->dbContents = Timestamp::getUNIXtime();
		$cache->update();
		unset($cache);
	}
	return $target;
}

function showCoverPhoto_purgeCache($target, $mother) {
	global $database, $blogid;
	requireComponent('Needlworks.Cache.PageCache');
	CacheControl::flushCategory();

	$cache = new pageCache;
	$showCoverPhotos = POD::queryColumn("SELECT name
			FROM {$database['prefix']}PageCacheLog
			WHERE blogid = ".$blogid."
			AND name like 'JP\\_ShowCoverPhoto\\_%'");
	foreach($showCoverPhotos as $showCoverPhotoName){
		$cache->reset();
		$cache->name = $showCoverPhotoName;
		$cache->purge();
	}
	unset($cache);
	return $target;
}

function getThumbnailCategoryPopup($target) {
	global $blogid;
	require_once('lang/pluginLocal.php');
	?>
	<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
	<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>썸네일 카테고리 선택 팝업</title>
		<style type="text/css">
			body {margin:10px;}
			#title {
				font:12px dotum;
				font-weight:bold;
			}
			#categorySelect{
				font:11px dotum;width:180px;
			}
		</style>
		<script type="text/javascript">
			function categoryInsert(categoryId){
				opener.document.getElementsByName('categoryName')[0].value = categoryId;
				window.close();
			}
		</script>
	</head>
	<body>
	<div id="title">카테고리 선택</div>
	<?php
	$categoryHtml .= '<select id="categorySelect" onchange="categoryInsert(this.value);" size="10">'.CRLF;
	foreach (getCategories($blogid) as $category) {
		if ($category['id'] != 0) {
			$categoryHtml .= '<option value="' . $category['id'] .'">&nbsp;' . ($category['visibility'] > 1 ? '' : _t('(비공개)')) . htmlspecialchars($category['name']) . '</option>'.CRLF;
		}
		foreach ($category['children'] as $child) {
			if ($category['id'] != 0) {
				$categoryHtml .= '<option value="' . $child['id'] . '">&nbsp;&nbsp;&nbsp;&bull; ' . ($category['visibility'] > 1 && $child['visibility'] > 1 ? '' : _t('(비공개)')) . htmlspecialchars($child['name']) .'</option>'.CRLF;
			}
		}
	}

	$categoryHtml .= '</select></body></html>';

	echo $categoryHtml;
}

// ################################################################################################################
// ## Thumbnail List & Sidebar & Cover Setting ############################################################################
// ################################################################################################################
function showThumbStyle($target){
	global $blogURL, $pluginURL, $pluginName, $service;
	$blogid = getBlogId();
	requireComponent('Textcube.Function.misc');
	$pluginInfo = getPluginInformation($pluginName);
	$style = "";
	if (file_exists(ROOT . "/cache/thumbnail/".$blogid."/JP_Thumb/jp_thumb_style.css")) {
		$style  = "<link rel=\"stylesheet\" type=\"text/css\" href=\"".$service['path']."/thumbnail/{$blogid}/JP_Thumb/jp_thumb_style.css\" />".CRLF;
	}
	$style .= "<!-- ".CRLF;
	$style .= "	J.Parker Thumbnail List/Sidebar/Cover View Plugin v".$pluginInfo['version']." for Textcube v1.6.3 ~ v1.8.* - http://create74.com".CRLF;
	$style .= "	DQ'Thumb Engine ver 2.0 R5.0306 for developer - http://www.dqstyle.com".CRLF;
	$style .= "-->	".CRLF;
	$target .= $style;
	return $target;
}

function getThumbStyle($data, $mode){
	requireComponent('Textcube.Function.misc');
	$data['bordercolor'] = (strpos($data['bordercolor'], "#")===0)?$data['bordercolor']:"#".$data['bordercolor'];
	if($mode == "style"){
		$style = '';
		ob_start();
		echo '
			/* Thumbnail List css setting for List */
			#thumb_main{margin:'.$data['mainmargin'].';}
			#thumb_main .thumb_item{margin:'.$data['itemmargin'].';text-align:'.$data['align'].';}
			#thumb_main .thumb_item .thumb_image {margin:0;padding:0;}
			#thumb_main .thumb_item .thumb_border{margin:'.$data['imagemargin'].';border:'.$data['bordersize'].' solid '.$data['bordercolor'].';}
			#thumb_main .thumb_item .thumb_title {height:14px;}
			#thumb_main .thumb_item .thumb_title a {'.$data['titlefontset'].'}
			#thumb_main .thumb_item .thumb_title .thumb_cnt {'.$data['commentfontset'].'}
			#thumb_main .thumb_item .thumb_date {margin:1px 0px 0px 0px;'.$data['datefontset'].' letter-spacing:0px;}

			/* Thumbnail Sidebar css setting for Sidebar */
			#sidebarphotos_main{margin:'.$data['sb_mainmargin'].';}
			#sidebarphotos_main .thumb_item{margin:'.$data['sb_itemmargin'].';text-align:'.$data['sb_align'].';}
			#sidebarphotos_main .thumb_item .thumb_image {margin:0;padding:0;}
			#sidebarphotos_main .thumb_item .thumb_border{margin:0px 0px 0px 0px;border:'.$data['sb_bordersize'].' solid '.$data['sb_bordercolor'].';}
			#sidebarphotos_main .thumb_item .thumb_title {margin:2px 0px 0px 0px;height:14px;}
			#sidebarphotos_main .thumb_item .thumb_title a {'.$data['sb_titlefontset'].'}
			#sidebarphotos_main .thumb_item .thumb_title .thumb_cnt {'.$data['sb_commentfontset'].'}
			#sidebarphotos_main .thumb_item .thumb_date {margin:1px 0px 0px 0px;'.$data['sb_datefontset'].' letter-spacing:0px;}

			/* Thumbnail Cover css setting for Cover */
			.coverphotos_main{margin:'.$data['cv_mainmargin'].';}
			.coverphotos_main .thumb_item{margin:'.$data['cv_itemmargin'].';text-align:'.$data['cv_align'].';}
			.coverphotos_main .thumb_item .thumb_image {margin:0;padding:0;}
			.coverphotos_main .thumb_item .thumb_border{margin:0px 0px 0px 0px;border:'.$data['cv_bordersize'].' solid '.$data['cv_bordercolor'].';}
			.coverphotos_main .thumb_item .thumb_title {height:14px;}
			.coverphotos_main .thumb_item .thumb_title a {'.$data['cv_titlefontset'].'}
			.coverphotos_main .thumb_item .thumb_title .thumb_cnt {'.$data['cv_commentfontset'].'}
			.coverphotos_main .thumb_item .thumb_date {margin:1px 0px 0px 0px;'.$data['cv_datefontset'].' letter-spacing:0px;}
		';
		$style = ob_get_contents();
		ob_end_clean();
	}
	$style = str_replace(TAB, '', $style);
	return $style;
}

function ThumbnailClearStyle() {
	$blogid = getBlogId();
	if (file_exists(ROOT . "/cache/thumbnail/".$blogid."/JP_Thumb/jp_thumb_style.css"))
		@unlink(ROOT . "/cache/thumbnail/".$blogid."/JP_Thumb/jp_thumb_style.css");
}

function ThumbnailMakeStyle($data) {
	$blogid = getBlogId();
	$path = ROOT . '/cache/thumbnail/'.$blogid.'/JP_Thumb';
	if(!is_dir($path)) {
		getThumbDirectoryCheck();
	}
	$path .= "/jp_thumb_style.css";
	$fileHandle = fopen($path, 'w');
	if (fwrite($fileHandle, getThumbStyle($data, 'style'))) {
		@chmod($path, 0666);
		$result = true;
	} else $result = false;
	fclose($fileHandle);
}

function getAttachmentExtract_Thumb($content){
	global $blogid, $service;
	$result = null;
	if(preg_match_all('/\[##_(1R|1L|1C|2C|3C|iMazing|Gallery)\|[^|]*\.(gif|jpg|jpeg|png|bmp|GIF|JPG|JPEG|PNG|BMP)\|.*_##\]/si', $content, $matches)) {
		$split = explode("|", $matches[0][0]);
		$result = $split[1];
	}else if(preg_match_all('/<img[^>]+?src=("|\')?([^\'">]*?)("|\')/si', $content, $matches)) {
		$attachPath_1 = $service['path']."/attach/{$blogid}/";
		$attachPath_2 = "[##_ATTACH_PATH_##]";
		if ((strpos($matches[2][0], $attachPath_1) === 0) || (strpos($matches[2][0], $attachPath_2) === 0)){
			$result = basename($matches[2][0]);
		}else{
			$result = $matches[2][0];
		}
	}
	return $result;
}

function getAttachCheck_Thumb($ext){
	if (in_array($ext, array('jpg','jpeg','png','gif','thumb'))) return true;
	else return false;
}

function getCategoryArray($categories) {
	global $blogURL;
	$tree = array('id'=>'','label'=>'','value'=>'','link'=>'','children'=>array());
	foreach($categories as $category1){
		$children=array();
		foreach($category1['children'] as $category2){
			array_push($children,array('id'=>$category2['id'],'label'=>$category2['name'],'value'=>(doesHaveOwnership()?$category2['entriesInLogin']:$category2['entries']),'link'=>"$blogURL/category/".rawurlencode($category2['label']),'children'=>array()));
		}
		if($category1['id'] != 0) {
			array_push($tree['children'],array('id'=>$category1['id'],'label'=>$category1['name'],'value'=>(doesHaveOwnership()?$category1['entriesInLogin']:$category1['entries']),'link'=>"$blogURL/category/".rawurlencode($category1['label']),'children'=>$children));
		}
	}
	return $tree;
}

function getCategoriesThumbnail() {
	global $blogid, $blogURL;
	$categories = getCategories($blogid);
	$tree = getCategoryArray($categories);
	$cntA = 0;
	$cntB = '';
	$cntC = 0;
	$manifest = '';
	foreach($tree['children'] as $child){
		$cntA++;
		$cntC++;
		if(count($child['children'])){$br1 = "<br>";}else{$br1="";}
		$manifest .= '<op name="c'.$cntA.'" value="'.$child['id'].'"><![CDATA[<b><font color="#8D4143" title="카테고리 ID : '.$child['id'].'번.">'.htmlspecialchars($child['label']).'</font></b>'.$br1.']]></op>'.CRLF;
		$cntB = "";
		foreach($child['children'] as $leaf){
			$cntA++;
			$cntB++;
			if($cntB == count($child['children'])){$br2 = "<br>";}else{$br2="";}
			if((count($categories) == $cntC) && ($cntB == count($child['children']))) $br2="";
			$manifest .= '<op name="c'.$cntA.'" value="'.$leaf['id'].'"><![CDATA[<font color="#777777" title="카테고리 ID : '.$leaf['id'].'번.">'.htmlspecialchars($leaf['label']).'</font>'.$br2.']]></op>'.CRLF;
		}
	}
	return $manifest;
}

function CFG_ThumbnailSet($plugin){
	global $database, $blogid, $configVal;
	requireComponent('Textcube.Function.misc');
	require_once('lang/pluginLocal.php');
	$data = misc::fetchConfigVal($configVal);
	$count = POD::queryCell("SELECT count(*) FROM {$database['prefix']}Categories WHERE blogid = $blogid AND id > 0 ORDER BY parent, priority");
	$setCategory = array();
	for($i=1; $i <= $count; $i++){
		$data['c'.$i] = isset($data['c'.$i]) ? $data['c'.$i] : "";
		if($data['c'.$i])
		array_push($setCategory, getCategoryNameById($blogid, $data['c'.$i]));
	}
	if (substr(file_get_contents(ROOT.'/cache/CHECKUP'), 0, 3) < 1.5) {
		$_text = pluginLang::plts('업데이트 안내 ::\r\n - 사용하고 계시는 썸네일 플러그인은 Textcube 1.5 이상에서만 사용 가능합니다. \r\n 업데이트 후 다시 시도 하시기 바랍니다.');
		$setupAlert = '<script type="text/javascript">alert(":: '.$_text.'"); self.close();</script>';
	}else{
		$_text = pluginLang::plts('설정변경 안내 ::\r\n - 썸네일이미지(리스트/사이드바/표지) 하단의 제목, 댓글, 날짜 폰트에 대한   \r\n   설정 방법이 변경되었습니다.  \r\n - 재설정 하시고 저장해주셔야 합니다.  \r\n * 확인버튼 클릭 후 저장하시면 알림창이 표시되지 않습니다.   \r\n   (확인하시면 자동체크 됩니다.');
		$setupAlert = (!isset($data['alertfont']))?'<script type="text/javascript">alert(":: '.$_text.')");document.getElementById("alertfont").checked = true;</script>':'';
	}
	$manifest = NULL;
	$manifest .= '<?xml version="1.0" encoding="utf-8"?>'.CRLF;
	$manifest .= '<config dataValHandler="ThumbnailDataSet">'.CRLF;
	$manifest .= '	<window width="500" height="700" />'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('사용 안내').'" >'.CRLF;
	$manifest .= '		<field title=" " name="alertView" type="checkbox" titledirection="bk">'.CRLF;
	$manifest .= '			<op name="alertfont" value="1"><![CDATA[ '.pluginLang::plts('알림창 확인하셨으면, 체크하시고 저장하세요.').$setupAlert.']]></op>'.CRLF;
	if (!function_exists('gd_info')) {
		$manifest .= '			<caption><![CDATA['.pluginLang::plts('<font color="red"><b>알림:</b> 이미지 가공에 필요한 <b><font color="blue"><u>GD Library</u></font></b>가 미 설치된 상태입니다. 호스팅 관리자에게 문의 해보시기 바랍니다. </font>').']]></caption>'.CRLF;
	}else{
		$fileType = array('jpg', 'gif', 'png', 'bmp');
		$errType = array();
		foreach ($fileType as $type){
			if(getGDSupport($type) == false){
				array_push($errType, $type);
			}
		}
		if(count($errType) > 0){
			$errType = strtoupper(implode(',', $errType));
			$manifest .= '			<caption><![CDATA['.pluginLang::plfs('<b>알림:</b> <b><font color="blue"><u>GD Library</u></font></b>가 설치되어 있지만 <font color="red"><b>%1</b></font> 파일 타입은 지원하지 않습니다. 호스팅 관리자에게 문의 해보시기 바랍니다.',$errType).']]></caption>'.CRLF;
		}
	}
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('썸네일 플러그인 사용 범위 선택').'" >'.CRLF;
	$manifest .= '		<field title=" " name="attachCheckItem" type="checkbox" titledirection="bk">'.CRLF;
	$manifest .= '			<op name="uList" value="1" checked="checked"><![CDATA[ <b><font color="green">List</font></b>&nbsp;&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="uSide" value="1" checked="checked"><![CDATA[ <b><font color="green">SideBar</font></b>&nbsp;&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="uCover" value="1" checked="checked"><![CDATA[ <b><font color="green">Coverpage</font></b>&nbsp;&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="uNull" value="1"><![CDATA[ <b><font color="#aa3300">'.pluginLang::plts('모두 사용안함').'</font></b>]]></op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> \'<u>List</u>\', \'<u>SideBar</u>\', \'<u>Coverpage</u>\' 선택되어도 \'<u><font color=red>모두 사용안함</font></u>\'이 선택되면 적용 안됩니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('썸네일 카테고리 선택').'" >'.CRLF;
	$manifest .= '		<field title="　" name="category" type="checkbox" titledirection="bk">'.CRLF;
	$manifest .= '			<op name="call" value="1"><![CDATA[<b><font color="blue">All Category</font></b><br>]]></op>'.CRLF;
	$manifest .=			getCategoriesThumbnail();
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> <b><u><font color="blue">All Category</font></u></b> 선택시 <font color="red"><u>다른 카테고리</u></font>는 선택할수 없습니다.<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;말그대로 모든 카테고리 리스트를 썸네일 이미지로 보여집니다.<br><b>tip:</b> 썸네일 이미지를 적용할 카테고리를 체크하세요.<br><b>tip:</b> <b><font color="#8D4143">진한 빨간색</font></b>이 상위카테고리 입니다. 상위 카테고리만 선택을 해도 하위 카테고리 모두 적용됩니다. 또한, 하위 카테고리만 개별 선택해도 됩니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('썸네일 리스트 표시 설정').'" >'.CRLF;
	$manifest .= '		<field title=" " name="showListOnCategory" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="2" checked="checked"><![CDATA['.pluginLang::plts('썸네일 목록만 표시합니다.').' <br/>]]></op>'.CRLF;
	$manifest .= '			<op value="3"><![CDATA['.pluginLang::plts('썸네일 목록과 한 쪽당 글 수 만큼 글을 표시합니다.').' <br/>]]></op>'.CRLF;
	$manifest .= '			<op value="1"><![CDATA['.pluginLang::plts('썸네일 목록과 함께 해당되는 모든 글을 표시합니다.').' <br/>]]></op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('썸네일 리스트 적용 추가범위 선택').'" >'.CRLF;
	$manifest .= '		<field title=" " name="photoblog" type="checkbox" titledirection="bk">'.CRLF;
	$manifest .= '			<op name="p1" value="1"><![CDATA[ <b><font color="green">Archive List</font></b>&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="p2" value="1"><![CDATA[ <b><font color="green">Search List</font></b>&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="p3" value="1"><![CDATA[ <b><font color="green">Tag List</font></b>&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="p4" value="1"><![CDATA[ <b><font color="green">Author List</font></b>]]></op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> <b><u><font color="blue">All Category</font></u></b> 기본 선택시 함께 사용할 수 있습니다.<br><b>tip:</b> 사용하는 블로그가 포토 전용인 경우 권장합니다.(<u><font color="red">포토블로그 강추</font></u>).').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('썸네일 적용 파일 선택').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 적용범위').'" name="attachCheckItem" type="checkbox" titledirection="bk">'.CRLF;
	$manifest .= '			<op name="fList" value="1" checked="checked"><![CDATA[<b><font color="blue">List</font></b>&nbsp;&nbsp; &nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="fSide" value="1" checked="checked"><![CDATA[<b><font color="blue">SideBar</font></b>]]></op>'.CRLF;
	$manifest .= '			<op name="fCover" value="1" checked="checked"><![CDATA[<b><font color="blue">Coverpage</font></b>]]></op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title=" " name="thumbnailAttach" type="checkbox" titledirection="bk" >'.CRLF;
	$manifest .= '			<op name="f1" value="1" checked="checked"><![CDATA[<b><font color="green">.JPG</font></b>&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="f2" value="1" checked="checked"><![CDATA[<b><font color="green">.JPEG</font></b>&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="f3" value="1" checked="checked"><![CDATA[<b><font color="green">.GIF</font></b>&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="f4" value="1" checked="checked"><![CDATA[<b><font color="green">.PNG</font></b>&nbsp;&nbsp;]]></op>'.CRLF;
	$manifest .= '			<op name="f5" value="1" checked="checked"><![CDATA[<b><font color="#D88787">ALL Files</font></b>]]></op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 각각의 파일을 선택 해제하면, 해제된 파일이 존재하는 포스트는 썸네일 목록에서 제외됩니다.<br><b>tip:</b> \'<b><font color="#D88787">ALL Files</font></b>\'를 선택하게 되면 썸네일 이미지로 변환 못시키는 파일과 포스트 내에 파일이 존재하지 않을때 <u>대체이미지</u>로 표시됩니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title=" : '.pluginLang::plts('링크 이미지').'" name="urlimg" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1" checked="checked">ON</op>'.CRLF;
	$manifest .= '			<op value="2">OFF</op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> \'<b><font color=blue>&lt;img&gt;</font></b>\' 태그로 링크된 이미지를 썸네일화 시킵니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title=" : '.pluginLang::plts('보호되어 있는 글 썸네일 표시').'" name="lockimg" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">'.pluginLang::plts('공개').'</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">'.pluginLang::plts('보호').'</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('이미지 품질').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 품질(0~100)').'" name="quality" type="text" size="3" titledirection="bk" value="95" />'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('이미지 주변 자르기').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 원본 주변 자르기').'" name="cutpixel" type="text" size="3" titledirection="bk" value="5" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 원본이미지에 특정 틀이 있을때 원본 주변을 정해진 값만큼 잘라줍니다.<br><b>tip:</b> 리사이즈 방식이 \'<b>원본비율+가운데자름</b>\' 선택시만 적용 됩니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('리스트 설정').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 가로크기').'" name="width" type="text" size="3" titledirection="bk" value="82" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 세로크기').'" name="height" type="text" size="3" titledirection="bk" value="122" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시될 썸네일 가로갯수').'" name="maxX" type="text" size="3" titledirection="bk" value="5" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시될 썸네일 세로갯수').'" name="maxY" type="text" size="3" titledirection="bk" value="8" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 리사이즈방식').'" name="resize" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">'.pluginLang::plts('원본비율대칭').'</op>'.CRLF;
	$manifest .= '			<op value="2">'.pluginLang::plts('비율유지안함').'</op>'.CRLF;
	$manifest .= '			<op value="3" checked="checked">'.pluginLang::plts('원본비율+가운데자름').'</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 제목 표시하기').'" name="title" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1" checked="checked">ON</op>'.CRLF;
	$manifest .= '			<op value="2">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시할 제목길이').'" name="title_length" type="text" size="3" titledirection="bk" value="11" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 댓글수 표시하기').'" name="comment" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1" checked="checked">ON</op>'.CRLF;
	$manifest .= '			<op value="2">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 날짜 표시하기').'" name="date" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1" checked="checked">ON</op>'.CRLF;
	$manifest .= '			<op value="2">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : LightBox플러그인 기능 적용하기').'" name="lightbox" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b><a href="http://moonmelody.com/tt/" target="_blank">치리님</a></b>의 LightBox플러그인이 설치되어 있으면 썸네일 클릭시 LightBox 형태로 원본이미지표시됨. (link : <a href="http://moonmelody.com/tt/entry/LightboxTTAZmanualNqna" target="_blank">Lightbox TT AZ</a>)').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('리스트 스타일(CSS) 설정').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 가로 정렬').'" name="align" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="left">Left</op>'.CRLF;
	$manifest .= '			<op value="center" checked="checked">Center</op>'.CRLF;
	$manifest .= '			<op value="right">Right</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 세로 정렬').'" name="valign" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="top">Top</op>'.CRLF;
	$manifest .= '			<op value="middle">Middle</op>'.CRLF;
	$manifest .= '			<op value="bottom" checked="checked">Bottom</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 리스트 메인 바깥여백').'" name="mainmargin" type="text" size="20" titledirection="bk" value="20px 0px 0px 3px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 리스트 서브 바깥여백').'" name="itemmargin" type="text" size="20" titledirection="bk" value="0px 6px 10px 5px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 바깥여백').'" name="imagemargin" type="text" size="20" titledirection="bk" value="0px 0px 5px 0px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 테두리 사이즈').'" name="bordersize" type="text" size="4" titledirection="bk" value="4px" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 테두리색').'" name="bordercolor" type="text" size="8" titledirection="bk" value="#E8E6E2" >'.CRLF;
	$manifest .= '			<caption><![CDATA[<b>tip:</b> #D7SDFS or D7SDFS, #d7sdfs or d7sdfs]]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 제목 글꼴/색상').'" name="titlefontset" type="text" size="45" titledirection="bk" value="font:11px dotum; color:#555555;" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 댓글 글꼴/색상').'" name="commentfontset" type="text" size="45" titledirection="bk" value="font:7pt tahoma; color:#999999;" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 날짜 글꼴/색상').'" name="datefontset" type="text" size="45" titledirection="bk" value="font:7pt tahoma; color:#555555;" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 글꼴 크기는 \'pt\', \'px\', \'em\'등 단위를 포함해야 함.<br><b>tip:</b> 기본형식은 \'<b>font:11px dotum; color:#555555;</b>\'와 같아야 합니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('리스트 메인 HTML Header').'">'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts('* 사용중인 skin.html 참고').'" name="header" cols="51" rows="3"  type="textarea" titledirection="bk" ><![CDATA[<div class="searchList">'.CRLF;
	$manifest .= pluginLang::plts('<h3><span class="keycolor">\'[##_list_conform_##]\'</span>에 해당되는 글 [##_list_count_##]건 </h3>').']]></field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('리스트 메인 HTML Footer').'">'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts('* 사용중인 skin.html 참고').'" name="footer" cols="51" rows="3"  type="textarea" titledirection="bk" ><![CDATA[</div>]]>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('사이드바 썸네일 설정').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 가로크기').'" name="sb_width" type="text" size="3" titledirection="bk" value="40" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 세로크기').'" name="sb_height" type="text" size="3" titledirection="bk" value="40" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시될 썸네일 가로갯수').'" name="sb_maxX" type="text" size="3" titledirection="bk" value="4" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시될 썸네일 세로갯수').'" name="sb_maxY" type="text" size="3" titledirection="bk" value="2" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 리사이즈방식').'" name="sb_resize" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">'.pluginLang::plts('원본비율대칭').'</op>'.CRLF;
	$manifest .= '			<op value="2">'.pluginLang::plts('비율유지안함').'</op>'.CRLF;
	$manifest .= '			<op value="3" checked="checked">'.pluginLang::plts('원본비율+가운데자름').'</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 이미지 로딩방식').'" name="sb_loading" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1" checked="checked">'.pluginLang::plts('최근등록순').'</op>'.CRLF;
	$manifest .= '			<op value="2">'.pluginLang::plts('랜덤').'</op>'.CRLF;
	$manifest .= '			<op value="3">'.pluginLang::plts('댓글순').'</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 제목 표시하기').'" name="sb_title" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시할 제목길이').'" name="sb_title_length" type="text" size="3" titledirection="bk" value="7" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 댓글수 표시하기').'" name="sb_comment" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 날짜 표시하기').'" name="sb_date" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : LightBox플러그인 기능 적용하기').'" name="sb_lightbox" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b><a href="http://moonmelody.com/tt/" target="_blank">치리님</a></b>의 LightBox플러그인이 설치되어 있으면 썸네일 클릭시 LightBox 형태로 원본이미지표시됨. (link : <a href="http://moonmelody.com/tt/entry/LightboxTTAZmanualNqna" target="_blank">Lightbox TT AZ</a>)').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('사이드바 썸네일 스타일(CSS) 설정').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 가로 정렬').'" name="sb_align" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="left">Left</op>'.CRLF;
	$manifest .= '			<op value="center" checked="checked">Center</op>'.CRLF;
	$manifest .= '			<op value="right">Right</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 세로 정렬').'" name="sb_valign" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="top" checked="checked">Top</op>'.CRLF;
	$manifest .= '			<op value="middle">Middle</op>'.CRLF;
	$manifest .= '			<op value="bottom">Bottom</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 사이드바 메인 바깥여백').'" name="sb_mainmargin" type="text" size="20" titledirection="bk" value="8px 2px 0px 5px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 사이드바 서브 바깥여백').'" name="sb_itemmargin" type="text" size="20" titledirection="bk" value="0px 2px 7px 3px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 바깥여백').'" name="sb_imagemargin" type="text" size="20" titledirection="bk" value="0px 0px 0px 0px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 테두리 사이즈').'" name="sb_bordersize" type="text" size="4" titledirection="bk" value="1px" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 테두리색').'" name="sb_bordercolor" type="text" size="8" titledirection="bk" value="#D9D5C7" >'.CRLF;
	$manifest .= '			<caption><![CDATA[<b>tip:</b> #D7SDFS or D7SDFS, #d7sdfs or d7sdfs]]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 제목 글꼴/색상').'" name="sb_titlefontset" type="text" size="45" titledirection="bk" value="font:11px dotum; color:#555555;" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 댓글 글꼴/색상').'" name="sb_commentfontset" type="text" size="45" titledirection="bk" value="font:7pt tahoma; color:#999999;" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 날짜 글꼴/색상').'" name="sb_datefontset" type="text" size="45" titledirection="bk" value="font:7pt tahoma; color:#555555;" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 글꼴 크기는 \'pt\', \'px\', \'em\'등 단위를 포함해야 함.<br><b>tip:</b> 기본형식은 \'<b>font:11px dotum; color:#555555;</b>\'와 같아야 합니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('사이드바 HTML Header').'">'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts('* 사용중인 skin.html 참고').'" name="sb_header" cols="51" rows="2"  type="textarea" titledirection="bk" ><![CDATA[<div class="sidebar_photos">'.CRLF;
	$manifest .= '<h3>sidebar photos</h3>]]></field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('사이드바 HTML Footer').'">'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts('* 사용중인 skin.html 참고').'" name="sb_footer" cols="51" rows="2"  type="textarea" titledirection="bk" ><![CDATA[</div>]]>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('표지 썸네일 설정').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 가로크기').'" name="cv_width" type="text" size="3" titledirection="bk" value="71" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 세로크기').'" name="cv_height" type="text" size="3" titledirection="bk" value="71" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시될 썸네일 가로갯수').'" name="cv_maxX" type="text" size="3" titledirection="bk" value="6" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시될 썸네일 세로갯수').'" name="cv_maxY" type="text" size="3" titledirection="bk" value="2" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 리사이즈방식').'" name="cv_resize" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">'.pluginLang::plts('원본비율대칭').'</op>'.CRLF;
	$manifest .= '			<op value="2">'.pluginLang::plts('비율유지안함').'</op>'.CRLF;
	$manifest .= '			<op value="3" checked="checked">'.pluginLang::plts('원본비율+가운데자름').'</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 이미지 로딩방식').'" name="cv_loading" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1" checked="checked">'.pluginLang::plts('최근등록순').'</op>'.CRLF;
	$manifest .= '			<op value="2">'.pluginLang::plts('랜덤').'</op>'.CRLF;
	$manifest .= '			<op value="3">'.pluginLang::plts('댓글순').'</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 제목 표시하기').'" name="cv_title" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표시할 제목길이').'" name="cv_title_length" type="text" size="3" titledirection="bk" value="7" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 댓글수 표시하기').'" name="cv_comment" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 날짜 표시하기').'" name="cv_date" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : LightBox플러그인 기능 적용하기').'" name="cv_lightbox" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="1">ON</op>'.CRLF;
	$manifest .= '			<op value="2" checked="checked">OFF</op>'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b><a href="http://moonmelody.com/tt/" target="_blank">치리님</a></b>의 LightBox플러그인이 설치되어 있으면 썸네일 클릭시 LightBox 형태로 원본이미지표시됨. (link : <a href="http://moonmelody.com/tt/entry/LightboxTTAZmanualNqna" target="_blank">Lightbox TT AZ</a>)').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('표지 썸네일 스타일(CSS) 설정').'" >'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 가로 정렬').'" name="cv_align" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="left">Left</op>'.CRLF;
	$manifest .= '			<op value="center" checked="checked">Center</op>'.CRLF;
	$manifest .= '			<op value="right">Right</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 세로 정렬').'" name="cv_valign" type="radio" titledirection="bk" >'.CRLF;
	$manifest .= '			<op value="top">Top</op>'.CRLF;
	$manifest .= '			<op value="middle">Middle</op>'.CRLF;
	$manifest .= '			<op value="bottom" checked="checked">Bottom</op>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표지 메인 바깥여백').'" name="cv_mainmargin" type="text" size="20" titledirection="bk" value="5px 0px 0px 0px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 표지 서브 바깥여백').'" name="cv_itemmargin" type="text" size="20" titledirection="bk" value="0px 3px 5px 3px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 바깥여백').'" name="cv_imagemargin" type="text" size="20" titledirection="bk" value="0px 0px 5px 0px" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 20px 1px 2px 1px , [상px 우px 하px 좌px]').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 테두리 사이즈').'" name="cv_bordersize" type="text" size="4" titledirection="bk" value="4px" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 썸네일 이미지 테두리색').'" name="cv_bordercolor" type="text" size="8" titledirection="bk" value="#E8E6E2" >'.CRLF;
	$manifest .= '			<caption><![CDATA[<b>tip:</b> #D7SDFS or D7SDFS, #d7sdfs or d7sdfs]]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 제목 글꼴/색상').'" name="cv_titlefontset" type="text" size="45" titledirection="bk" value="font:11px dotum; color:#555555;" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 댓글 글꼴/색상').'" name="cv_commentfontset" type="text" size="45" titledirection="bk" value="font:7pt tahoma; color:#999999;" />'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts(' : 날짜 글꼴/색상').'" name="cv_datefontset" type="text" size="45" titledirection="bk" value="font:7pt tahoma; color:#555555;" >'.CRLF;
	$manifest .= '			<caption><![CDATA['.pluginLang::plts('<b>tip:</b> 글꼴 크기는 \'pt\', \'px\', \'em\'등 단위를 포함해야 함.<br><b>tip:</b> 기본형식은 \'<b>font:11px dotum; color:#555555;</b>\'와 같아야 합니다.').']]></caption>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('표지 HTML Header').'">'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts('* 사용중인 skin.html 참고').'" name="cv_header" cols="51" rows="2"  type="textarea" titledirection="bk" ><![CDATA[<div class="cover_photos">]]></field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '	<fieldset legend="'.pluginLang::plts('표지 HTML Footer').'">'.CRLF;
	$manifest .= '		<field title="'.pluginLang::plts('* 사용중인 skin.html 참고').'" name="cv_footer" cols="51" rows="2"  type="textarea" titledirection="bk" ><![CDATA[</div>]]>'.CRLF;
	$manifest .= '		</field>'.CRLF;
	$manifest .= '	</fieldset>'.CRLF;
	$manifest .= '</config>';

	return $manifest;
}

function ThumbnailDataSet($DATA){
	$blogid = getBlogId();

	requireComponent('Textcube.Function.misc');
	require_once('lang/pluginLocal.php');
	$cfg = misc::fetchConfigVal($DATA);
	$categories = getCategories($blogid);
	$ctArray = array(); $setCategory = array(); $pArray = array(); $fArray = array();
	foreach($categories as $category1){
		foreach($category1['children'] as $category2) array_push($ctArray, $category2['children']);
		array_push($ctArray, $category1['children']);
	}
	for($i=0; $i<=count($ctArray); $i++){
		if($cfg['c'.$i])
		array_push($setCategory, $cfg['c'.$i]);
	}
	for($j=0; $j<=4; $j++){
		if($cfg['p'.$j])
		array_push($pArray, $cfg['p'.$j]);
	}
	for($k=0; $k<=5; $k++){
		if($cfg['f'.$k])
		array_push($fArray, $cfg['f'.$k]);
	}

	if(!$cfg['uList'] && !$cfg['uSide'] && !$cfg['uCover'] && !$cfg['uNull']) return pluginLang::plts('::선택 오류::\r\n썸네일 플러그인 사용 범위는 적어도 하나이상 선택하셔야 합니다.');
	if(!$cfg['call'] && count($setCategory)==0) return pluginLang::plts('::선택 오류::\r\n썸네일 카테고리는 적어도 하나이상 선택하셔야 합니다.');
	if($cfg['call']  && count($setCategory)!=0) return pluginLang::plts('::선택 오류::\r\n\'All Category\' 선택시 다른 카테고리는 선택할 수 없습니다.');
	if(!$cfg['call'] && count($pArray)!=0)		return pluginLang::plts('::선택 오류::\r\n\'추가범위 선택\'은 \'All Category\' 기본 선택시 함께 사용할 수 있습니다.');
	if(count($fArray)==0)						return pluginLang::plts('::선택 오류::\r\n\'썸네일 적용 파일 선택\'은 적어도 하나이상 선택하셔야 합니다.');

	ThumbnailClearStyle();
	ThumbnailMakeStyle($cfg);

	return true;
}
?>